package controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import model.DataTableObject;
import model.Manufacturer;
import model.ManufacturerInfo;
import model.Product;
import model.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import dao.IManufacturerDAO;
import dao.IProductDAO;
import dao.IUserDAO;

@Controller
public class DataController {
	
	@Autowired
	@Qualifier("manufacturerServices")
	private IManufacturerDAO manuDao;
	
	@Autowired
	@Qualifier("productServices")
	private IProductDAO productDao;
	
	@Autowired
	@Qualifier("userServices")
	private IUserDAO userDao;
	
	User tempUser = null;

	static  Logger log = Logger.getLogger(CRUDController.class.getName());

	public DataController() {
		log.info("Init Data Controller");
	}
	
	@RequestMapping(value = "/dataManufacturer", method = RequestMethod.GET)
	@ResponseBody
	public String doTest(HttpSession session) {
		List<Manufacturer> myManufacture = null;
		tempUser = (User) session.getAttribute("userInfo");
		try {
			log.info("Going to get Manufacturer By User ID");
			myManufacture = manuDao.getManuFactureByUId(tempUser.getId());
		} catch (Exception e) {
			log.error("Exception: ", e);
		}
		if(myManufacture== null){
			return "{\"aaData\":{}}";
		}
		DataTableObject<Manufacturer> dataTableObj = new DataTableObject<Manufacturer>();
		dataTableObj.setAaData(myManufacture);
		log.info("Going to sent List of Manufacturer By User ID using Gson");
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String data = gson.toJson(dataTableObj);
		log.info("data of Manufacturer: " + data);
		return data;
	}
	
	@RequestMapping(value = "/dataUserRequest", method = RequestMethod.POST)
	@ResponseBody
	public String getUserRequest(){
		List<User> myUser = null;
		try {
			myUser = userDao.getUserByRole("-1");
		} catch (Exception e) {
			log.error("Exception", e);
		}
		
		if(myUser== null){
			
			return "{\"aaData\":{}}";
		}
		
		DataTableObject<User> dataTableObj = new DataTableObject<User>();
		dataTableObj.setAaData(myUser);
		log.info("Going to sent List of User By Role using Gson");
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String data = gson.toJson(dataTableObj);
		System.out.println("data user by role: "+ data);
		return data;
	}
	
	@RequestMapping(value = "/searchProduct", method = RequestMethod.POST)
	@ResponseBody
	public String searchProduct(@RequestBody String requestJson){
		System.out.println(requestJson);
		List<Product> tempProduct = null;
		List<Product> tempPriceProduct = new ArrayList<Product>();
		List<Product> tempNameProduct = new ArrayList<Product>();
		List<Product> totalProduct = new ArrayList<Product>();
		totalProduct.clear();
		List<String> tempId = null;
		JsonParser parser = new JsonParser();
		Object obj = parser.parse(requestJson);
		JsonObject jsonObject = (JsonObject) obj;
		String manufactureName = "";
		manufactureName= jsonObject.get("manufactureName").toString();
		if(manufactureName.length() > 2){	
			manufactureName = manufactureName.substring(1, manufactureName.length()-1 );
			String []conditionManuName;
			conditionManuName = manufactureName.split(",");
			if(conditionManuName.length > 0){
				for (int i = 0; i < conditionManuName.length; i++) {
					tempId = manuDao.getIdManufacturerViaName(conditionManuName[i].trim());
					for (String a : tempId) {
						tempProduct = productDao.getAllProductBy_M_ID(Integer.parseInt(a));
						if(tempProduct != null){
							totalProduct.addAll(tempProduct);
						}
					}
				}
			}
			
			
		}else {
			tempProduct = productDao.getAllProduct();
			totalProduct.addAll(tempProduct);
		}
		String productName = "";
		productName = jsonObject.get("productName").toString();
		if(productName.length() > 2){
			productName = productName.substring(1, productName.length()-1 );
			String []conditionProductName;
			conditionProductName = productName.split(",");
			if(tempProduct != null){
				tempProduct.clear();
			}
			if(conditionProductName.length > 0){
				tempNameProduct.clear();
				for (int k = 0; k < conditionProductName.length; k++) {
					tempProduct = productDao.getAllProductByName(conditionProductName[k].trim());
					if(tempProduct != null){
						tempNameProduct.addAll(tempProduct);
					}
				}
				for(int i = 0; i<totalProduct.size(); i++){
					int count = 0;
					for(int j = 0 ; j<tempNameProduct.size(); j++){
						if(totalProduct.get(i).getId().toString().equals(tempNameProduct.get(j).getId().toString())){
							count++;
						}
					}
					if (count == 0) {
						totalProduct.remove(i);
						i--;
					}
				}
			}
		}else {
			if(tempProduct != null){
				tempProduct.clear();
			}
		}
		
		String price = "";
		price = jsonObject.get("price").toString();
		if(price.length()>2){
			price = price.substring(1, price.length()-2 );
			String []conditionPrice;
			String []detailPrice;
			conditionPrice = price.split(",");
			tempPriceProduct.clear();
			if(conditionPrice.length > 0){
				for (int i = 0; i < conditionPrice.length; i++) {
					System.out.println(conditionPrice[i]);
					detailPrice = conditionPrice[i].split("~");
					if(tempProduct != null){
						tempProduct.clear();
					}
					
					if(detailPrice.length == 2){
							tempProduct = productDao.getAllProductByPrice(Double.parseDouble(detailPrice[0]), Double.parseDouble(detailPrice[1]));
							if(tempProduct != null){
								tempPriceProduct.addAll(tempProduct);
							}
					}
					if(detailPrice.length == 1 && !detailPrice[0].toString().contains("")){
							tempProduct = productDao.getAllProductByPrice(Double.parseDouble(detailPrice[0]), 100000);
							if(tempProduct != null){
								tempPriceProduct.addAll(tempProduct);
							}
					}				
				}
			}
			
			if(tempPriceProduct.size() != 0){
				for(int i = 0; i<totalProduct.size(); i++){
					int count = 0;
					for(int j = 0 ; j<tempPriceProduct.size(); j++){	
						if(totalProduct.get(i).getId().toString().equals(tempPriceProduct.get(j).getId().toString())){
							count++;
						}
					}
					if(count == 0){
						totalProduct.remove(i);
						i--;
					}
				}
			}
		}
		
		if(totalProduct.size() != 0){
			Gson gson = new Gson();
			return gson.toJson(totalProduct);
		}
		return "";
	}
	

	@RequestMapping(value = "/dataProduct", method = RequestMethod.GET)
	@ResponseBody
	public String getDataProduct(HttpSession session) {
		User usr = (User) session.getAttribute("userInfo");
		List<Manufacturer> myManufacturerList = null;
		List<Product> myProductList=null;
		
		try {
			log.info("Going to get Prduct Info");
			myProductList = productDao.getAllProductBy_U_ID(Integer
					.parseInt(usr.getId()));
		} catch (Exception e) {
			log.error("Exception: ", e);
		}
		
		if(myProductList== null){
			
			return "{\"aaData\":{}}";
		}
		
		
		try {
			log.info("Going to get list of product by User ID");
			myManufacturerList = manuDao.getManuFactureByUId((usr.getId()));
		} catch (Exception e) {
			log.error("Exception: ", e);
		}
		
		for (Product product : myProductList) {
			for (Manufacturer manufacturer : myManufacturerList) {
				if (manufacturer.getId().equals(product.getM_id())) {
					product.setM_id(manufacturer.getName());
				}
			}
		}

		log.info("Going to send list of product by User ID");
		DataTableObject<Product> dataTableObj = new DataTableObject<Product>();
		dataTableObj.setAaData(myProductList);
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String data = gson.toJson(dataTableObj);
		log.info("data of Product: " + data);
		return data;
	}

	@RequestMapping(value = "/manufacturerInfo", method = RequestMethod.GET)
	@ResponseBody
	public String getManufacturerInfo(HttpSession session) {
		List<ManufacturerInfo> manufacturerInfoList = new ArrayList<ManufacturerInfo>();
		List<Manufacturer> myManufacture = null;
		tempUser = (User) session.getAttribute("userInfo");

		try {
			log.info("Going to get Manufacter info");
			myManufacture = manuDao.getManuFactureByUId(tempUser.getId());
		} catch (Exception e) {
			log.error("Exception", e);
		}
		for (Manufacturer manufacturer : myManufacture) {
			ManufacturerInfo manufacturerInfo = new ManufacturerInfo();
			manufacturerInfo.setId(manufacturer.getId());
			manufacturerInfo.setName(manufacturer.getName());
			manufacturerInfoList.add(manufacturerInfo);
		}
		log.info("Going to send Manufacter info");
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String data = gson.toJson(manufacturerInfoList);
		System.out.println("data of Manufacturer INFO: " + data);
		return data;
	}

}
